// 图案管理云对象
module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
	},

	/**
	 * 获取图案列表
	 * @param {string} category 分类
	 * @param {number} page 页码
	 * @param {number} limit 每页数量
	 * @param {string} keyword 搜索关键词
	 * @param {string} sortBy 排序方式
	 * @returns {object} 图案列表
	 */
	async getPatternList({category, page = 1, limit = 20, keyword, sortBy = 'create_time'}) {
		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			let whereCondition = {
				status: 1  // 只获取已发布的图案
			};
			
			// 分类筛选
			if (category && category !== 'all') {
				whereCondition.category = category;
			}
			
			// 关键词搜索
			if (keyword) {
				whereCondition = dbCmd.and([
					whereCondition,
					dbCmd.or([
						{pattern_name: new RegExp(keyword, 'i')},
						{pattern_name_en: new RegExp(keyword, 'i')},
						{tags: dbCmd.in([new RegExp(keyword, 'i')])}
					])
				]);
			}
			
			// 排序条件
			let orderBy = 'create_time';
			let orderType = 'desc';
			
			switch (sortBy) {
				case 'popular':
					orderBy = 'download_count';
					break;
				case 'newest':
					orderBy = 'create_time';
					break;
				case 'favorite':
					orderBy = 'favorite_count';
					break;
				case 'name':
					orderBy = 'pattern_name';
					orderType = 'asc';
					break;
			}
			
			// 分页查询
			const skip = (page - 1) * limit;
			const patternResult = await db.collection('sh_user_pattern')
				.where(whereCondition)
				.orderBy(orderBy, orderType)
				.skip(skip)
				.limit(limit)
				.get();
			
			// 获取总数
			const countResult = await db.collection('sh_user_pattern')
				.where(whereCondition)
				.count();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					list: patternResult.data,
					total: countResult.total,
					page,
					limit,
					totalPages: Math.ceil(countResult.total / limit)
				}
			}
		} catch (error) {
			console.error('获取图案列表失败:', error);
			return {
				errCode: 'GET_PATTERN_LIST_FAILED',
				errMsg: '获取图案列表失败'
			}
		}
	},

	/**
	 * 获取图案详情
	 * @param {string} patternId 图案ID
	 * @returns {object} 图案详情
	 */
	async getPatternDetail({patternId}) {
		if (!patternId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '图案ID不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			const patternResult = await db.collection('sh_user_pattern').doc(patternId).get();
			
			if (patternResult.data.length === 0) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不存在'
				}
			}

			// 更新下载次数
			await db.collection('sh_user_pattern').doc(patternId).update({
				download_count: db.command.inc(1),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: patternResult.data[0]
			}
		} catch (error) {
			console.error('获取图案详情失败:', error);
			return {
				errCode: 'GET_PATTERN_DETAIL_FAILED',
				errMsg: '获取图案详情失败'
			}
		}
	},

	/**
	 * 获取分类列表
	 * @returns {object} 分类列表
	 */
	async getCategoryList() {
		try {
			const categories = [
				{id: 'all', name: '全部', name_en: 'All'},
				{id: 'nature', name: '自然', name_en: 'Nature'},
				{id: 'animal', name: '动物', name_en: 'Animal'},
				{id: 'abstract', name: '抽象', name_en: 'Abstract'},
				{id: 'geometry', name: '几何', name_en: 'Geometry'},
				{id: 'art', name: '艺术', name_en: 'Art'},
				{id: 'other', name: '其他', name_en: 'Other'}
			];

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: categories
			}
		} catch (error) {
			console.error('获取分类列表失败:', error);
			return {
				errCode: 'GET_CATEGORY_LIST_FAILED',
				errMsg: '获取分类列表失败'
			}
		}
	},

	/**
	 * 获取精选图案
	 * @param {number} limit 数量限制
	 * @returns {object} 精选图案列表
	 */
	async getFeaturedPatterns({limit = 10}) {
		try {
			const db = uniCloud.database();
			
			const patternResult = await db.collection('sh_user_pattern')
				.where({
					status: 1,
					is_featured: true
				})
				.orderBy('create_time', 'desc')
				.limit(limit)
				.get();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: patternResult.data
			}
		} catch (error) {
			console.error('获取精选图案失败:', error);
			return {
				errCode: 'GET_FEATURED_PATTERNS_FAILED',
				errMsg: '获取精选图案失败'
			}
		}
	},

	/**
	 * 获取热门图案
	 * @param {number} limit 数量限制
	 * @returns {object} 热门图案列表
	 */
	async getPopularPatterns({limit = 10}) {
		try {
			const db = uniCloud.database();
			
			const patternResult = await db.collection('sh_user_pattern')
				.where({
					status: 1
				})
				.orderBy('download_count', 'desc')
				.limit(limit)
				.get();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: patternResult.data
			}
		} catch (error) {
			console.error('获取热门图案失败:', error);
			return {
				errCode: 'GET_POPULAR_PATTERNS_FAILED',
				errMsg: '获取热门图案失败'
			}
		}
	},

	/**
	 * 添加图案到收藏
	 * @param {string} patternId 图案ID
	 * @param {string} collectionId 收藏集ID（可选）
	 * @returns {object} 添加结果
	 */
	async addToFavorite({patternId, collectionId}) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			let userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}
			
			if (!patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查是否已收藏
			const existFavorite = await db.collection('sh_user_favorite').where({
				user_id: userId,
				pattern_id: patternId
			}).get();

			if (existFavorite.data.length > 0) {
				return {
					errCode: 'ALREADY_FAVORITED',
					errMsg: '已在收藏列表中'
				}
			}

			// 添加收藏
			await db.collection('sh_user_favorite').add({
				user_id: userId,
				pattern_id: patternId,
				collection_id: collectionId || null,
				create_time: new Date()
			});

			// 更新图案收藏次数
			await db.collection('sh_user_pattern').doc(patternId).update({
				favorite_count: db.command.inc(1),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '添加收藏成功'
			}
		} catch (error) {
			console.error('添加收藏失败:', error);
			return {
				errCode: 'ADD_FAVORITE_FAILED',
				errMsg: '添加收藏失败'
			}
		}
	},

	/**
	 * 从收藏中移除
	 * @param {string} patternId 图案ID
	 * @returns {object} 移除结果
	 */
	async removeFromFavorite({patternId}) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			let userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}
			
			if (!patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 删除收藏记录
			const removeResult = await db.collection('sh_user_favorite').where({
				user_id: userId,
				pattern_id: patternId
			}).remove();

			if (removeResult.deleted === 0) {
				return {
					errCode: 'FAVORITE_NOT_FOUND',
					errMsg: '收藏记录不存在'
				}
			}

			// 更新图案收藏次数
			await db.collection('sh_user_pattern').doc(patternId).update({
				favorite_count: db.command.inc(-1),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '取消收藏成功'
			}
		} catch (error) {
			console.error('取消收藏失败:', error);
			return {
				errCode: 'REMOVE_FAVORITE_FAILED',
				errMsg: '取消收藏失败'
			}
		}
	},

	/**
	 * 获取用户收藏列表
	 * @param {string} collectionId 收藏集ID（可选）
	 * @param {number} page 页码
	 * @param {number} limit 每页数量
	 * @returns {object} 收藏列表
	 */
	async getUserFavorites({collectionId, page = 1, limit = 20}) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			let userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			const db = uniCloud.database();
			const dbCmd = db.command;
			
			let whereCondition = {
				user_id: userId
			};
			
			if (collectionId) {
				whereCondition.collection_id = collectionId;
			} else {
				whereCondition.collection_id = dbCmd.or([null, '']);
			}
			
			// 分页查询收藏记录并关联图案信息
			const skip = (page - 1) * limit;
			const favoriteResult = await db.collection('sh_user_favorite')
				.aggregate()
				.match(whereCondition)
				.lookup({
					from: 'pattern',
					localField: 'pattern_id',
					foreignField: '_id',
					as: 'pattern'
				})
				.unwind('$pattern')
				.sort({create_time: -1})
				.skip(skip)
				.limit(limit)
				.end();

			// 获取总数
			const countResult = await db.collection('sh_user_favorite')
				.where(whereCondition)
				.count();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					list: favoriteResult.data,
					total: countResult.total,
					page,
					limit,
					totalPages: Math.ceil(countResult.total / limit)
				}
			}
		} catch (error) {
			console.error('获取收藏列表失败:', error);
			return {
				errCode: 'GET_FAVORITES_FAILED',
				errMsg: '获取收藏列表失败'
			}
		}
	},

	/**
	 * 切换图案收藏状态
	 * @param {string} patternId 图案ID
	 * @param {string} action 操作类型 add/remove
	 * @returns {object} 操作结果
	 */
	async togglePatternFavorite({ patternId, action }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			let userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			// 检查图案是否存在
			const patternResult = await db.collection('sh_user_pattern').doc(patternId).get();
			if (patternResult.data.length === 0) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不存在'
				}
			}

			// 检查是否已收藏
			const existResult = await db.collection('sh_user_favorite')
				.where({
					user_id: userId,
					pattern_id: patternId
				})
				.get();

			const isExist = existResult.data.length > 0;

			if (action === 'add') {
				if (isExist) {
					return {
						errCode: 'ALREADY_FAVORITED',
						errMsg: '已经收藏过了'
					}
				}

				// 添加收藏
				const favoriteData = {
					user_id: userId,
					pattern_id: patternId,
					collection_id: '', // 默认收藏集为空
					create_time: new Date()
				};

				await db.collection('sh_user_favorite').add(favoriteData);

				return {
					errCode: 0,
					errMsg: '收藏成功',
					data: { favorited: true }
				}
			} else if (action === 'remove') {
				if (!isExist) {
					return {
						errCode: 'NOT_FAVORITED',
						errMsg: '还未收藏'
					}
				}

				// 取消收藏
				await db.collection('sh_user_favorite').doc(existResult.data[0]._id).remove();

				return {
					errCode: 0,
					errMsg: '取消收藏成功',
					data: { favorited: false }
				}
			} else {
				// 自动切换收藏状态
				if (isExist) {
					// 取消收藏
					await db.collection('sh_user_favorite').doc(existResult.data[0]._id).remove();
					return {
						errCode: 0,
						errMsg: '取消收藏成功',
						data: { favorited: false }
					}
				} else {
					// 添加收藏
					const favoriteData = {
						user_id: userId,
						pattern_id: patternId,
						collection_id: '',
						create_time: new Date()
					};

					await db.collection('sh_user_favorite').add(favoriteData);
					return {
						errCode: 0,
						errMsg: '收藏成功',
						data: { favorited: true }
					}
				}
			}
		} catch (error) {
			console.error('切换收藏状态失败:', error);
			return {
				errCode: 'TOGGLE_FAVORITE_FAILED',
				errMsg: '操作失败'
			}
		}
	},

	/**
	 * 检查图案是否已收藏
	 * @param {string} patternId 图案ID
	 * @returns {object} 检查结果
	 */
	async checkFavorite({ patternId }) {
		try {
			const token = this.getUniIdToken()
			const uniID = UniID.createInstance({ context: this })
			const { code, uid, userInfo } = await uniID.checkToken(token)
			let userId = uid
			
			if (!userId) {
				return {
					errCode: 401,
					errMsg: '用户未登录'
				}
			}

			if (!patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			const existResult = await db.collection('sh_user_favorite')
				.where({
					user_id: userId,
					pattern_id: patternId
				})
				.get();

			return {
				errCode: 0,
				errMsg: '检查成功',
				data: {
					favorited: existResult.data.length > 0
				}
			}
		} catch (error) {
			console.error('检查收藏状态失败:', error);
			return {
				errCode: 'CHECK_FAVORITE_FAILED',
				errMsg: '检查失败'
			}
		}
	},

	/**
	 * 搜索图案（兼容前端API调用）
	 * @param {object} params 搜索参数
	 * @returns {object} 搜索结果
	 */
	async searchPatterns(params = {}) {
		return await this.getPatternList(params);
	},

	/**
	 * 获取图案详情
	 * @param {string} patternId 图案ID
	 * @returns {object} 图案详情
	 */
	async getPatternDetail({ patternId }) {
		try {
			if (!patternId) {
				return {
					errCode: 'PARAM_ERROR',
					errMsg: '图案ID不能为空'
				}
			}

			const db = uniCloud.database();
			
			const patternResult = await db.collection('sh_user_pattern').doc(patternId).get();
			
			if (patternResult.data.length === 0) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不存在'
				}
			}

			// 增加浏览次数
			await db.collection('sh_user_pattern').doc(patternId).update({
				view_count: db.command.inc(1)
			});

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: patternResult.data[0]
			}
		} catch (error) {
			console.error('获取图案详情失败:', error);
			return {
				errCode: 'GET_PATTERN_DETAIL_FAILED',
				errMsg: '获取图案详情失败'
			}
		}
	},

	/**
	 * 获取分类列表
	 * @returns {object} 分类列表
	 */
	async getCategories() {
		try {
			// 返回预定义的分类列表
			const categories = [
				{ id: 'all', name: '全部', name_en: 'All' },
				{ id: 'nature', name: '自然', name_en: 'Nature' },
				{ id: 'animal', name: '动物', name_en: 'Animal' },
				{ id: 'geometric', name: '几何', name_en: 'Geometric' },
				{ id: 'abstract', name: '抽象', name_en: 'Abstract' },
				{ id: 'portrait', name: '人物', name_en: 'Portrait' },
				{ id: 'landscape', name: '风景', name_en: 'Landscape' },
				{ id: 'flower', name: '花卉', name_en: 'Flower' },
				{ id: 'pattern', name: '图案', name_en: 'Pattern' }
			];

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: categories
			}
		} catch (error) {
			console.error('获取分类列表失败:', error);
			return {
				errCode: 'GET_CATEGORIES_FAILED',
				errMsg: '获取分类列表失败'
			}
		}
	},

	/**
	 * 获取推荐图案
	 * @returns {object} 推荐图案列表
	 */
	async getRecommendPatterns() {
		try {
			const db = uniCloud.database();
			
			const result = await db.collection('sh_user_pattern')
				.where({
					status: 1,
					is_recommend: true
				})
				.orderBy('recommend_sort', 'asc')
				.orderBy('create_time', 'desc')
				.limit(10)
				.get();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: result.data
			}
		} catch (error) {
			console.error('获取推荐图案失败:', error);
			return {
				errCode: 'GET_RECOMMEND_PATTERNS_FAILED',
				errMsg: '获取推荐图案失败'
			}
		}
	},

	/**
	 * 获取热门图案
	 * @returns {object} 热门图案列表
	 */
	async getHotPatterns() {
		try {
			const db = uniCloud.database();
			
			const result = await db.collection('sh_user_pattern')
				.where({
					status: 1
				})
				.orderBy('download_count', 'desc')
				.orderBy('view_count', 'desc')
				.limit(10)
				.get();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: result.data
			}
		} catch (error) {
			console.error('获取热门图案失败:', error);
			return {
				errCode: 'GET_HOT_PATTERNS_FAILED',
				errMsg: '获取热门图案失败'
			}
		}
	},

	/**
	 * 获取最新图案
	 * @returns {object} 最新图案列表
	 */
	async getNewPatterns() {
		try {
			const db = uniCloud.database();
			
			const result = await db.collection('sh_user_pattern')
				.where({
					status: 1
				})
				.orderBy('create_time', 'desc')
				.limit(10)
				.get();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: result.data
			}
		} catch (error) {
			console.error('获取最新图案失败:', error);
			return {
				errCode: 'GET_NEW_PATTERNS_FAILED',
				errMsg: '获取最新图案失败'
			}
		}
	}
}
